package tpoo.client;

import org.eclipse.jface.resource.ImageDescriptor;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.internal.util.BundleUtility;
import org.eclipse.ui.plugin.AbstractUIPlugin;
import org.osgi.framework.BundleContext;

import tpoo.client.controllers.handlers.LogoutHandler;
import tpoo.common.dto.model.users.UserDTO;
import tpoo.common.services.UserService;
import tpoo.common.services.utils.ServiceAdmin;
import tpoo.common.services.utils.ServiceConstants;
import tpoo.common.utils.Listener;
import tpoo.common.utils.UserSession;

/**
 * The activator class controls the plug-in life cycle
 */
public class Activator extends AbstractUIPlugin {

	// The plug-in ID
	public static final String PLUGIN_ID = "tpoo-client";

	// The shared instance
	private static Activator plugin;

	/**
	 * The constructor
	 */
	public Activator() {
		plugin = this;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#start(org.osgi.framework.BundleContext
	 * )
	 */
	public void start(BundleContext context) throws Exception {
		super.start(context);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.ui.plugin.AbstractUIPlugin#stop(org.osgi.framework.BundleContext
	 * )
	 */
	public void stop(BundleContext context) throws Exception {
		
		plugin = null;
		
		/*
		try {
			IHandlerService handlerService = (IHandlerService) PlatformUI.getWorkbench().getActiveWorkbenchWindow().getService(IHandlerService.class);
			handlerService.executeCommand(LogoutHandler.ID, null);
			
		} catch (Exception ex) {
			throw new RuntimeException(LogoutHandler.ID +" not found as a service");
		} finally {
			plugin = null;
			Listener.getListener().stop();
			super.stop(context);
		}*/

		
		try {
			if (UserSession.isSessionStarted()) {
				// TODO estaría bueno invocar al Handler logout
				UserDTO udto = UserSession.getInstance().getUser();
				UserService us = (UserService) ServiceAdmin
						.getService(ServiceConstants.USER_SERVICE);
				us.logout(udto);
			}
		} finally {
			super.stop(context);
		}
		
		
	}

	/**
	 * Returns the shared instance
	 * 
	 * @return the shared instance
	 */
	public static Activator getDefault() {
		return plugin;
	}

	/**
	 * Returns an image descriptor for the image file at the given plug-in
	 * relative path
	 * 
	 * @param path
	 *            the path
	 * @return the image descriptor
	 */
	public static ImageDescriptor getImageDescriptor(String path) {
		return imageDescriptorFromPlugin(PLUGIN_ID, path);
	}
}
